﻿using In66.Net.EventBus.RabbitMq.Abstraction;

namespace In66.Net.EventBus.RabbitMq.Manager;

internal sealed class ChannelPool : IChannelPool
{
    private IConnection _connection { get; set; }
    private uint _maxSize { get; set; }

    public ChannelPool(IConnection connection, uint maxSize)
    {
        _connection = connection;
        _maxSize = maxSize;
    }
    private readonly ConcurrentBag<IModel> _channels = new ConcurrentBag<IModel>();

    /// <inheritdoc />
    public IModel GetChannel() => _channels.TryTake(out var channel) ? channel : _connection.CreateModel();

    /// <inheritdoc />
    public void ReturnChannel(IModel channel)
    {
        if (_channels.Count <= _maxSize)
        {
            _channels.Add(channel);
            return;
        }
        channel.Dispose();
    }

    public void Dispose()
    {
        foreach (var channel in _channels)
        {
            channel.Dispose();
        }
    }
}